package com.web.cms.pan.dao;

import com.blue.jdbc.BaseDao;
import com.web.cms.pan.model.FolderFile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.Collection;

/**
 * 目录文件数据库访问
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2018年04月09日
 */
@Repository("panFolderFileDao")
public class FolderFileDao extends BaseDao<FolderFile>
{
	public FolderFileDao()
	{
	}
	
	@Override
	protected void query(StringBuilder sql, FolderFile param)
	{
		if (param != null)
		{
			if (param.getFolderId() != null && param.getFolderId() > -1)
				sql.append(" and a.folder_id=:folderId");

			if (param.getUserId() != null && param.getUserId() > 0)
				sql.append(" and a.user_id=:userId");

			if (param.getFileDataId() != null && param.getFileDataId() > 0)
				sql.append(" and a.file_data_id=:fileDataId");

			if (param.getType() != null)
				sql.append(" and a.type=:type");

			if (param.getState() != null)
				sql.append(" and a.state=:state");
		}
		sql.append(" order by a.name, a.file_data_id");
	}

	public void deleteById(Collection<Integer> idList)
	{
		if (idList == null || idList.isEmpty())
			return;

		String param = StringUtils.join(idList, ",");

		String sql = "insert into pan_delete_file_data (id, user_id, name, `key`, mime_type, create_time, type, size)" +
				" select f.id, f.user_id, f.name, f.`key`, f.mime_type, f.create_time, f.type, f.size from pan_file_data f" +
				" inner join pan_folder_file ff on f.id=ff.file_data_id where f.count=1 and ff.id in (%s)";
		jdbcTemplate.update(String.format(sql, param));

		sql = "delete from pan_file_data where count=1 and id in (select file_data_id from pan_folder_file where id in (%s))";
		jdbcTemplate.update(String.format(sql, param));

		sql = "update pan_file_data set count=count-1 where count>1 and id in (select file_data_id from pan_folder_file where id in (%s))";
		jdbcTemplate.update(String.format(sql, param));

		sql = "delete from pan_folder_file where id in(%s)";
		jdbcTemplate.update(String.format(sql, param));
	}

	public void copyByFolder(Integer srcId, Integer destId)
	{
		String sql = "insert into pan_folder_file (folder_id, file_data_id, user_id, name, `key`, type, file_size)" +
				" select ?, file_data_id, user_id, name, `key`, type, file_size from pan_folder_file where state=0 and folder_id=?";
		jdbcTemplate.update(sql, destId, srcId);

		sql = "update pan_file_data set count=count+1 where id in (select file_data_id from pan_folder_file where state=0 and folder_id=?)";
		jdbcTemplate.update(sql, destId);
	}
	
}
